#include <gtest/gtest.h>
#include "Thread/WorkThreadPool.h"
#include <atomic>
#include <thread>
#include <vector>

// - SingletonInstance : 测试单例模式
// - PoolSizeConfiguration : 测试线程池大小配置
// - GetPoller : 测试获取Poller功能
// - CpuAffinitySetting : 测试CPU亲和性设置
// - MultiThreadAccess : 测试多线程并发访问

using namespace toolkit;
using namespace std;

class WorkThreadPoolTest : public testing::Test {
protected:
    void SetUp() override {
        // 确保每次测试前重置单例状态
        WorkThreadPool::setPoolSize(0);
        WorkThreadPool::enableCpuAffinity(true);
    }
};

TEST_F(WorkThreadPoolTest, SingletonInstance) {
    auto& instance1 = WorkThreadPool::Instance();
    auto& instance2 = WorkThreadPool::Instance();
    
    // 验证单例模式
    EXPECT_EQ(&instance1, &instance2);
}

TEST_F(WorkThreadPoolTest, PoolSizeConfiguration) {
    const size_t testSize = 4;
    WorkThreadPool::setPoolSize(testSize);
    
    auto& pool = WorkThreadPool::Instance();
    auto poller = pool.getFirstPoller();
    
    // 验证线程池大小配置
    EXPECT_NE(poller, nullptr);
}

TEST_F(WorkThreadPoolTest, GetPoller) {
    auto& pool = WorkThreadPool::Instance();
    
    // 测试获取Poller
    auto poller1 = pool.getPoller();
    auto poller2 = pool.getPoller();
    
    EXPECT_NE(poller1, nullptr);
    EXPECT_NE(poller2, nullptr);
}

TEST_F(WorkThreadPoolTest, CpuAffinitySetting) {
    // 测试CPU亲和性设置
    WorkThreadPool::enableCpuAffinity(false);
    auto& pool = WorkThreadPool::Instance();
    auto poller = pool.getFirstPoller();
    
    EXPECT_NE(poller, nullptr);
}

TEST_F(WorkThreadPoolTest, MultiThreadAccess) {
    auto& pool = WorkThreadPool::Instance();
    atomic_int counter(0);
    const int taskCount = 100;
    
    vector<thread> threads;
    for (int i = 0; i < taskCount; ++i) {
        threads.emplace_back([&]() {
            auto poller = pool.getPoller();
            if (poller) {
                ++counter;
            }
        });
    }
    
    for (auto& t : threads) {
        t.join();
    }
    
    EXPECT_EQ(counter.load(), taskCount);
}